package com.xxkj.drugtraceability.ui.doctoradviceback

import android.view.View
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.LinearLayoutManager
import com.xxhis.refactor.eventbus.MessageCode
import com.xxkj.drugtraceability.R
import com.xxkj.drugtraceability.base.BaseVMActivity
import com.xxkj.drugtraceability.bean.*
import com.xxkj.drugtraceability.databinding.*
import com.xxkj.drugtraceability.dialog.BlueDialog
import com.xxkj.drugtraceability.dialog.YellowDialog
import com.xxkj.drugtraceability.ext.clickN
import com.xxkj.drugtraceability.lifecycle.KtxManager
import com.xxkj.drugtraceability.scan.BarcodeType.Companion.SUYUAN
import com.xxkj.drugtraceability.utils.showCompleteToast
import com.xxkj.drugtraceability.utils.toast
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import org.koin.androidx.viewmodel.ext.android.viewModel

/**
 * author: zhoujingjin
 * created on: 2024/9/10 14:43
 * description:医嘱退药采集
 */
class DoctorAdviceBackActivity : BaseVMActivity() {
    private val binding by binding<ActivityDoctoradvciebackBinding>(R.layout.activity_doctoradvcieback)
    private val viewModel by viewModel<DoctorAdviceBackViewModel>()
    private lateinit var adapterBottom: DoctorAdviceBackAdapter
    override fun initView() {
        binding.apply {
            toolBar.title = ""
            setSupportActionBar(toolBar)
            toolBar.setNavigationOnClickListener {
                onBackPressed()
            }
            recyclerView.layoutManager = LinearLayoutManager(this@DoctorAdviceBackActivity)

            adapterBottom = DoctorAdviceBackAdapter({ position ->
                val backItem = adapterBottom.data[position]
                var prescriptioninfo = mutableListOf<DoctorAdviceInfoBean>()
                prescriptioninfo.add(backItem)
                //保存数据
                viewModel.finishScanBackDrugCode(FinishAdviceRequest("2", prescriptioninfo, ""),backItem)
            }, {
                val patientIterator = adapterBottom.data.iterator()
                while (patientIterator.hasNext()) {
                    val patient = patientIterator.next()

                    // 删除空药品
                    val drugIterator = patient.drugInfoList.iterator()
                    while (drugIterator.hasNext()) {
                        val drug = drugIterator.next()
                        if (drug.drugTracInfoList.isNullOrEmpty()) {
                            drugIterator.remove()
                        }
                    }

                    // 删除空患者
                    if (patient.drugInfoList.isNullOrEmpty()) {
                        patientIterator.remove()
                    }
                }
                adapterBottom.notifyDataSetChanged()
                if (adapterBottom.data.isNullOrEmpty()) {
                    binding.llBottom.visibility = View.GONE
                    adapterBottom.setList(mutableListOf())
                    adapterBottom.setEmptyView(R.layout.layout_nodata)
                }


            })
            recyclerView.adapter = adapterBottom
            tvCancel.clickN {
                YellowDialog(
                    this@DoctorAdviceBackActivity, resources.getString(R.string.cancel_all)
                ) {
                    //清空所有追溯码
                    finish()
                }
            }
            tvClear.clickN {
                YellowDialog(
                    this@DoctorAdviceBackActivity, resources.getString(R.string.clear_all)
                ) {
                    //清数据
                    viewModel.prescriptioninfo.clear()
                    viewModel.update.postValue(true)
                }
            }
        }
    }

    override fun initData() {
        viewModel.update.postValue(true)
    }

    override fun startObserve() {
        viewModel.baseUiModel.observe(this, Observer {
            if (it.showLoading) {
                showMyDialog(resources.getString(R.string.getting_data))
            } else {
                dismissMyDialog()
            }
            if (!it.showError.isNullOrEmpty()) {
                BlueDialog(this, it.showError!!, type = 1) {}
            }
            if (it.showSuccess == true) {
                showCompleteToast(this)
            }
        })

        viewModel.update.observe(this, Observer { update ->
            if (update) {
                if (!viewModel.prescriptioninfo.isNullOrEmpty() && viewModel.prescriptioninfo.isNotEmpty()) {
                    adapterBottom.setNewInstance(viewModel.prescriptioninfo)
                    adapterBottom.notifyDataSetChanged()
                    binding.llBottom.visibility = View.VISIBLE
                } else {
                    binding.llBottom.visibility = View.GONE
                    adapterBottom.setList(mutableListOf())
                    adapterBottom.setEmptyView(R.layout.layout_nodata)
                }

            }

        })


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onGetMessage(message: EventMessage?) {
        message?.apply {
            //扫码拿到barcode了，去请求接口
            when (message.messageCode) {
                MessageCode.SCAN_BARCODE -> {
                    if (KtxManager.isTopActivity(this@DoctorAdviceBackActivity)) {
                        val barcodeMessage = this.any as BarcodeMessage
                        if (barcodeMessage.type == SUYUAN) {
                            if (adapterBottom.data.isNotEmpty()){
                                adapterBottom.data.forEach {
                                    it.drugInfoList.forEach { drugInfoList ->
                                        drugInfoList.drugTracInfoList?.forEach { drug ->
                                            if (drug.drugTracCodg == barcodeMessage.barcode) {
                                                toast(resources.getString(R.string.scan_code_has))
                                                return@apply
                                            }
                                        }

                                    }
                                }
                            }
                            viewModel.getSendBackList(barcodeMessage.barcode)
                        } else {
                            YellowDialog(
                                this@DoctorAdviceBackActivity,
                                resources.getString(R.string.scan_suyuan),
                                type = 1
                            ) {}
                        }


                    }
                }
            }
        }
    }

    override fun onStart() {
        super.onStart()
        if (!EventBus.getDefault().isRegistered(this)) EventBus.getDefault().register(this)
    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }
}